package com.dure.hotmemory.scenes;

import android.Manifest;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.text.Html;
import android.text.InputType;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.ScrollView;
import android.widget.TextView;

import com.dure.commonlib.util.DimentionUtil;
import com.dure.commonlib.util.NetworkUtil;
import com.dure.commonlib.util.PreferencesUtils;
import com.dure.commonlib.util.ToastUtils;
import com.dure.hotmemory.R;
import com.dure.hotmemory.adapters.CodeGridAdapter;
import com.dure.hotmemory.adapters.TopAdapter;
import com.dure.hotmemory.bean.Code;
import com.dure.hotmemory.bean.CodeDao;
import com.dure.hotmemory.bean.Level;
import com.dure.hotmemory.bean.Planet;
import com.dure.hotmemory.controllers.TrainingInfoController;
import com.dure.hotmemory.drawview.BaseSurfaceView;
import com.dure.hotmemory.listeners.ConfirmListener;
import com.dure.hotmemory.listeners.DialogCloseListener;
import com.dure.hotmemory.scenes.dzxl.BMXLScene;
import com.dure.hotmemory.scenes.dzxl.ScanScene;
import com.dure.hotmemory.scenes.jcxl.JDCYScene;
import com.dure.hotmemory.scenes.jcxl.JDTXScene;
import com.dure.hotmemory.scenes.jcxl.JDSZYScene;
import com.dure.hotmemory.scenes.jjxl.CXCYScene;
import com.dure.hotmemory.scenes.jjxl.CXTXScene;
import com.dure.hotmemory.scenes.jjxl.PKJYScene;
import com.dure.hotmemory.scenes.tzxl.CoupleImagesScene;
import com.dure.hotmemory.scenes.tzxl.GridMemoryScene;
import com.dure.hotmemory.scenes.tzxl.JYGWScene;
import com.dure.hotmemory.scenes.tzxl.MissingHanZiScene;
import com.dure.hotmemory.scenes.tzxl.PathFindView;
import com.dure.hotmemory.utils.DialogUtil;
import com.dure.hotmemory.utils.ShareUtil;
import com.socks.library.KLog;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by leix on 10/06/2017.
 */

public class TrainingInfoScene extends BaseScene {
    LinearLayout contentLL;
    TextView introduceTV;
    TextView paramsTV;
    TextView levelTV;
    Button planBtn, startBtn;
    TextView shareTV;
    TextView rewardTV, nameTV, numberTV;

    FrameLayout backFL;

    Planet planet;
    TrainingInfoController controller;
    private TopAdapter topAdapter;
    private ListView topLV;
    List<Code> codeList = new ArrayList<>();
    CodeGridAdapter adapter;
    Code currentSelectedCode;
    String type = "";
    private boolean codeListShowing = true;

    public TrainingInfoScene(BaseSurfaceView baseSurfaceView) {
        super(baseSurfaceView);
        controller = new TrainingInfoController(this);
        sceneView = LayoutInflater.from(activity).inflate(R.layout.training_info, null);
        initViews();
        activity.hideAd();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            backFL.setBackgroundResource(R.drawable.white_planet_drawable);
            shareTV.setBackgroundResource(R.drawable.white_planet_drawable);
            rewardTV.setBackgroundResource(R.drawable.white_planet_drawable);
        }else{
            backFL.setBackgroundResource(R.drawable.white_circle_drawable);
            shareTV.setBackgroundResource(R.drawable.white_circle_drawable);
            rewardTV.setBackgroundResource(R.drawable.white_circle_drawable);
        }
    }

    private void initViews() {
        backFL = (FrameLayout) sceneView.findViewById(R.id.back_fl);

        shareTV = (TextView) sceneView.findViewById(R.id.share_iv);
        rewardTV = (TextView) sceneView.findViewById(R.id.reward_iv);
        nameTV = (TextView) sceneView.findViewById(R.id.name_tv);
        numberTV = (TextView) sceneView.findViewById(R.id.number_tv);

        introduceTV = (TextView) sceneView.findViewById(R.id.introduce_tv);
        paramsTV = (TextView) sceneView.findViewById(R.id.params_tv);
        levelTV = (TextView) sceneView.findViewById(R.id.level_tv);
        contentLL = (LinearLayout) sceneView.findViewById(R.id.content_ll);
        planBtn = (Button) sceneView.findViewById(R.id.scan_code);
        startBtn = (Button) sceneView.findViewById(R.id.start_btn);

        addListener();
    }

    private void addListener() {
        backFL.setOnClickListener(activity);
        rewardTV.setOnClickListener(activity);
        shareTV.setOnClickListener(activity);
        planBtn.setOnClickListener(activity);
        startBtn.setOnClickListener(activity);
        introduceTV.setOnClickListener(activity);
        paramsTV.setOnClickListener(activity);
        levelTV.setOnClickListener(activity);
    }

    public void setCurrentPlanet(Planet planet) {
        this.planet = planet;
        initView();
    }

    private void initView() {
        nameTV.setText(planet.planet);
        if (TextUtils.equals(planet.parent_planet.alias, "dzxl")) {
            introduceTV.setText("编码");
            levelTV.setVisibility(View.GONE);
            planBtn.setText("浏览");
            startBtn.setText("练习");


            initCodeView();
        } else {
            introduceTV.setText("介绍");
            paramsTV.setVisibility(View.GONE);
            levelTV.setVisibility(View.VISIBLE);
            planBtn.setVisibility(View.GONE);
            numberTV.setVisibility(View.GONE);
            showIntroduce();
        }
    }

    private void showIntroduceOrCode() {
        if (TextUtils.equals(planet.parent_planet.alias, "dzxl")) {
            initCodeView();
        } else {
            showIntroduce();
        }

    }

    private void showIntroduce() {
        contentLL.removeAllViews();
        ScrollView scrollView = new ScrollView(activity);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);

        LinearLayout linearLayout = new LinearLayout(activity);

        TextView textView = new TextView(activity);

        textView.setTextColor(Color.WHITE);

        textView.setText(Html.fromHtml(planet.introduce));

        linearLayout.addView(textView, params);

        scrollView.setScrollbarFadingEnabled(true);

        scrollView.addView(linearLayout);

        contentLL.addView(scrollView);
    }

    @Override
    public void onRestart() {
        super.onRestart();
        if (adapter != null && codeListShowing) {
            initCodeView();
        }
    }

    private void initCodeView() {
        contentLL.removeAllViews();

        GridView gridView = new GridView(activity);
        gridView.setNumColumns(4);
        gridView.setHorizontalSpacing(10);
        gridView.setVerticalSpacing(10);


        adapter = new CodeGridAdapter(activity);

        if (TextUtils.equals(planet.parent_planet.alias, "dzxl")) {
            type = planet.alias;
            final CodeDao codeDao = activity.daoSession.getCodeDao();

            final List<Code> codeList = codeDao.queryBuilder()
                    .where(CodeDao.Properties.Type.eq(planet.alias), CodeDao.Properties.Position.eq(0))
                    .orderAsc(CodeDao.Properties.Index)
                    .list();
            if (codeList.size() > 0){
                setCodeList(codeList);
            }else{
                controller.loadCodeList(planet);
            }

        }

        KLog.d("lesleixz","codelist size = " + codeList.size());
        adapter.setDataList(codeList);

        gridView.setAdapter(adapter);

        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                currentSelectedCode = adapter.getItem(i);
                currentSelectedCode.type = type;
                controller.checkPermission(Manifest.permission.READ_EXTERNAL_STORAGE, 1, new ConfirmListener() {
                    @Override
                    public void confirmed(Bundle bundle) {

                        controller.showCodeDetailDialog(currentSelectedCode, new ConfirmListener() {
                            @Override
                            public void confirmed(Bundle bundle) {
                                boolean isClose = bundle.getBoolean("isClose");
                                if (isClose) {
//                                    adapter.notifyDataSetChanged();
                                    initCodeView();
                                } else {
                                    EditCodeScene editCodeScene = new EditCodeScene(baseSurfaceView);
                                    CodeDao codeDao = activity.daoSession.getCodeDao();
                                    List<Code> codeList = codeDao.queryBuilder()
                                            .where(CodeDao.Properties.Number.eq(currentSelectedCode.number), CodeDao.Properties.Type.eq(currentSelectedCode.type))
                                            .orderAsc(CodeDao.Properties.Position)
                                            .list();
                                    editCodeScene.setCodeList(codeList);
                                    activity.moveToNewScene(editCodeScene);
                                }

                            }
                        });
                    }
                });

            }
        });

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        params.setMargins(10, 10, 10, 10);
        contentLL.addView(gridView, params);
    }

    public void setCodeList(List<Code> codeList) {
        if (codeList != null && codeList.size() > 0) {
            this.codeList.clear();
            this.codeList.addAll(codeList);
            adapter.setDataList(this.codeList);
            numberTV.setText("数量：" + codeList.size());

            if (!TextUtils.equals(planet.alias, "sz")) {
                PreferencesUtils.putInt(activity, planet.alias + ":start_index", 0);
                PreferencesUtils.putInt(activity, planet.alias + ":end_index", codeList.size() - 1);
            }
        }

    }

    private void initParams() {
        contentLL.removeAllViews();

        ScrollView scrollView = new ScrollView(activity);
        ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        LinearLayout containerLL = new LinearLayout(activity);
        containerLL.setOrientation(LinearLayout.VERTICAL);
        scrollView.addView(containerLL, params);
        contentLL.addView(scrollView, params);

        View view = LayoutInflater.from(activity).inflate(R.layout.bian_ma_params, null);
        final LinearLayout paramsLL = (LinearLayout) view.findViewById(R.id.input_params_ll);
        final LinearLayout optionsLL = (LinearLayout) view.findViewById(R.id.options_ll);
        RadioGroup radioGroup = (RadioGroup) view.findViewById(R.id.radio_group);

        if (TextUtils.equals(planet.alias, "sz")) {
            optionsLL.setVisibility(View.VISIBLE);
            int selectedIndex = PreferencesUtils.getInt(activity, planet.alias + ":selected_index", 0);
            radioGroup.check(radioGroup.getChildAt(selectedIndex).getId());
            radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                    int startIndex = 0;
                    int endIndex = 0;
                    int selectedIndex = 0;
                    switch (checkedId) {
                        case R.id.first_selection_rb:
                            startIndex = 0;
                            endIndex = 9;
                            selectedIndex = 0;
                            break;
                        case R.id.second_selection_rb:
                            startIndex = 10;
                            endIndex = 29;
                            selectedIndex = 1;
                            break;
                        case R.id.third_selection_rb:
                            startIndex = 30;
                            endIndex = 49;
                            selectedIndex = 2;
                            break;
                        case R.id.forth_selection_rb:
                            startIndex = 50;
                            endIndex = 69;
                            selectedIndex = 3;
                            break;
                        case R.id.fifth_selection_rb:
                            startIndex = 70;
                            endIndex = 89;
                            selectedIndex = 4;
                            break;
                        case R.id.sixth_selection_rb:
                            startIndex = 90;
                            endIndex = 109;
                            selectedIndex = 5;
                            break;
                        case R.id.seventh_selection_rb:
                            startIndex = 0;
                            endIndex = 109;
                            selectedIndex = 6;
                            break;
                    }

                    PreferencesUtils.putInt(activity, planet.alias + ":start_index", startIndex);
                    PreferencesUtils.putInt(activity, planet.alias + ":end_index", endIndex);
                    PreferencesUtils.putInt(activity, planet.alias + ":selected_index", selectedIndex);
                }
            });
        }

        showInputParams(paramsLL);

        containerLL.addView(view);

    }

    private void showInputParams(LinearLayout paramsLL) {
        String[] paramsArr = {"切换时间(s)"};
        String[] enNameArr = {"change_time"};
        for (int i = 0; i < paramsArr.length; i++) {
            View view = LayoutInflater.from(activity).inflate(R.layout.param_item, null);
            TextView titleTV = (TextView) view.findViewById(R.id.title_tv);
            final TextView changeTV = (TextView) view.findViewById(R.id.change_tv);
            titleTV.setText(paramsArr[i]);
            final EditText inputET = (EditText) view.findViewById(R.id.input_et);
            final ImageView lockIV = (ImageView) view.findViewById(R.id.locker_iv);

            int value = PreferencesUtils.getInt(activity, planet.alias + ":" + enNameArr, 1);
            inputET.setText(String.valueOf(value));
            inputET.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL);


            if (PreferencesUtils.getBoolean(activity, "paied") || PreferencesUtils.getBoolean(activity, "share_success")) {
                lockIV.setVisibility(View.GONE);
                changeTV.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        String content = changeTV.getText().toString();
                        if (TextUtils.equals(content, "修改")) {
                            changeTV.setText("保存");
                            inputET.setEnabled(true);
                            inputET.setSelection(inputET.getText().length());
                        } else {
                            String value = inputET.getText().toString();

                            if (!TextUtils.isEmpty(value)) {
                                changeTV.setText("修改");
                                inputET.setEnabled(false);
                                PreferencesUtils.putFloat(activity, planet.alias + ":change_time", Float.valueOf(value));
                            } else {
                                ToastUtils.show(activity, "参数值不能为空");
                            }

                        }
                    }
                });
            } else {
                lockIV.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        DialogUtil.showShareDialog(activity, planet, "分享", "分享一次后可以开启所有训练参数的自定义",
                                new ConfirmListener() {
                                    @Override
                                    public void confirmed(Bundle bundle) {
                                        PreferencesUtils.putBoolean(activity, "share_success", true);
                                        lockIV.setVisibility(View.GONE);
                                        initParams();
                                    }
                                });
                    }
                });
            }
            paramsLL.addView(view);
        }
    }

    /**
     * 显示测试训练的前10
     */
    private void showTop() {
        contentLL.removeAllViews();
        View view = LayoutInflater.from(activity).inflate(R.layout.top_layout, null);
        topLV = (ListView) view.findViewById(R.id.top_lv);
        topAdapter = new TopAdapter(activity);
        topLV.setAdapter(topAdapter);

        contentLL.addView(view);
    }

    public void setAdapterData(List<Level> data) {
        topAdapter.setData(data);
    }

    public Planet getPlanet() {
        return planet;
    }

    @Override
    public void permissionGranted(int requestCode) {
        super.permissionGranted(requestCode);
        if (requestCode == 0) {
            ShareUtil.showCustomShareDialog(activity, planet, new ConfirmListener() {
                @Override
                public void confirmed(Bundle bundle) {
                    PreferencesUtils.putBoolean(activity, "share_success", true);
                    initParams();
                }
            });
        } else if (requestCode == 1) {
            controller.showCodeDetailDialog(currentSelectedCode, new ConfirmListener() {
                @Override
                public void confirmed(Bundle bundle) {
                    EditCodeScene editCodeScene = new EditCodeScene(baseSurfaceView);
                    CodeDao codeDao = activity.daoSession.getCodeDao();
                    List<Code> codeList = codeDao.queryBuilder()
                            .where(CodeDao.Properties.Number.eq(currentSelectedCode.number), CodeDao.Properties.Type.eq(type))
                            .orderAsc(CodeDao.Properties.Position)
                            .list();
                    editCodeScene.setCodeList(codeList);
                    activity.moveToNewScene(editCodeScene);
                }
            });
        }

    }


    @Override
    public void viewClicked(View view) {
        int padding = DimentionUtil.dpToPx(activity, 10);
        switch (view.getId()) {
            case R.id.back_fl:
                activity.onBackPressed();
                break;
            case R.id.share_iv:

                controller.checkPermission(Manifest.permission.READ_EXTERNAL_STORAGE, 0, new ConfirmListener() {
                    @Override
                    public void confirmed(Bundle bundle) {
                        ShareUtil.showCustomShareDialog(activity, planet, new ConfirmListener() {
                            @Override
                            public void confirmed(Bundle bundle) {
                                PreferencesUtils.putBoolean(activity, "share_success", true);
                                initParams();
                            }
                        });
                    }
                });
                break;
            case R.id.reward_iv:
                DialogUtil.showRewardDialog(activity, new ConfirmListener() {
                    @Override
                    public void confirmed(Bundle bundle) {
                        String amountStr = bundle.getString("amount");
                        double amount = 0;
                        if (!TextUtils.isEmpty(amountStr)) {
                            amount = Double.valueOf(amountStr);
                        }

                        PayScene payScene = new PayScene(baseSurfaceView);
                        payScene.setPayType("reward");
                        payScene.setAmount(amount);
                        activity.moveToNewScene(payScene);

                    }
                });
                break;
            case R.id.introduce_tv:
                codeListShowing = true;
                introduceTV.setBackgroundResource(R.drawable.white_button_drawable);
                introduceTV.setTextColor(activity.getResources().getColor(R.color.text_color_drawable));
                introduceTV.setPadding(0, padding, 0, padding);
                paramsTV.setBackgroundResource(R.color.transparent);
                paramsTV.setTextColor(Color.WHITE);
                levelTV.setBackgroundResource(R.color.transparent);
                levelTV.setTextColor(Color.WHITE);
                showIntroduceOrCode();
                break;
            case R.id.params_tv:
                codeListShowing = false;
                introduceTV.setBackgroundResource(R.color.transparent);
                introduceTV.setTextColor(Color.WHITE);
                paramsTV.setBackgroundResource(R.drawable.white_button_drawable);
                paramsTV.setTextColor(activity.getResources().getColor(R.color.text_color_drawable));
                paramsTV.setPadding(0, padding, 0, padding);
                levelTV.setBackgroundResource(R.color.transparent);
                levelTV.setTextColor(Color.WHITE);
                initParams();
                break;
            case R.id.scan_code:
                PreferencesUtils.putString(activity, "current_alias", planet.alias);
                ScanScene scanScene = new ScanScene(baseSurfaceView);
                scanScene.setCodeList(codeList);
                activity.moveToNewScene(scanScene);
                break;
            case R.id.start_btn:
                if (PreferencesUtils.getBoolean(activity, "login_success")
                        && !PreferencesUtils.getBoolean(activity, "paied")) {
                    if (NetworkUtil.isNetworkAvailable(activity)) {
                        if (!TextUtils.equals(planet.parent_planet.alias, "dzxl")
                                && !PreferencesUtils.hasKey(activity, planet.alias + ":best")) {
                            controller.getTrainingData(planet.alias);
                        } else {
                            startTraining();
                        }
                    } else {
                        startTraining();
                    }
                } else {
                    startTraining();
                }

                break;
            case R.id.level_tv:
                introduceTV.setBackgroundResource(R.color.transparent);
                introduceTV.setTextColor(Color.WHITE);
                levelTV.setBackgroundResource(R.drawable.white_button_drawable);
                levelTV.setTextColor(activity.getResources().getColor(R.color.text_color_drawable));
                levelTV.setPadding(0, padding, 0, padding);
                showTop();
                controller.getTop(planet.alias);

//                // 如果是第一次则显示提示对话框
//                if (!PreferencesUtils.getBoolean(activity, "isShowedInTop")) {
//                    PreferencesUtils.putBoolean(activity, "isShowedInTop", true);
//                    DialogUtil.showTowBtnDialog(activity, "温馨提示", "vip才可以永久保存训练数据并参与排名哦！", "关闭", "支付(50)", new DialogCloseListener() {
//                        @Override
//                        public void deniedClose(Bundle bundle) {
//
//                        }
//
//                        @Override
//                        public void confirmedClose(Bundle bundle) {
//                            PayScene payScene = new PayScene(baseSurfaceView);
//                            activity.moveToNewScene(payScene);
//                            payScene.setPayType("plan_pay");
//                            payScene.setAmount(50);
//                        }
//                    });
//                }

                break;
        }
    }

    private void startTraining() {
        KLog.d("lesleixz","before start alias = "+planet.alias);
        PreferencesUtils.putString(activity, "current_alias", planet.alias);// 这个赋值必需放在初始化下面scene之前

        BaseScene baseScene = null;
        if (TextUtils.equals(planet.parent_planet.alias, "dzxl")) {
            BMXLScene bmxlScene = new BMXLScene(baseSurfaceView);
            bmxlScene.setCodeList(codeList);
            baseScene = bmxlScene;
        } else if (TextUtils.equals(planet.parent_planet.alias, "tzxl")) {
            if (!PreferencesUtils.getBoolean(activity, "login_success")){
                // 显示登录对话框
                ToastUtils.show(activity, "请先登录");
                return;
            }else if (!PreferencesUtils.getBoolean(activity, "paied")){
                // 显示支付对话框
                DialogUtil.showTowBtnDialog(activity, "开启训练", "vip才可以进行挑战训练哦！", "关闭", "支付(50)", new DialogCloseListener() {
                    @Override
                    public void deniedClose(Bundle bundle) {

                    }

                    @Override
                    public void confirmedClose(Bundle bundle) {
                        PayScene payScene = new PayScene(baseSurfaceView);

                        payScene.setPayType("plan_pay");
                        payScene.setAmount(50);
                        activity.moveToNewScene(payScene);
                    }
                });
                return;
            }else{
                if (TextUtils.equals(planet.alias, "ljzz")) {
                    baseScene = new PathFindView(baseSurfaceView);
                } else if (TextUtils.equals(planet.alias, "fgjy")) {
                    baseScene = new GridMemoryScene(baseSurfaceView);
                } else if (TextUtils.equals(planet.alias, "txpd")) {
                    baseScene = new CoupleImagesScene(baseSurfaceView);
                } else if (TextUtils.equals(planet.alias, "jygw")) {
                    baseScene = new JYGWScene(baseSurfaceView);
                } else if (TextUtils.equals(planet.alias, "hzcd")) {
                    baseScene = new MissingHanZiScene(baseSurfaceView);
                }
            }
        } else {
            if (TextUtils.equals(planet.alias, "jdtx")) {
                baseScene = new JDTXScene(baseSurfaceView);
            } else if (TextUtils.equals(planet.alias, "jdsz")) {
                baseScene = new JDSZYScene(baseSurfaceView);
            } else if (TextUtils.equals(planet.alias, "jdcy")) {
                baseScene = new JDCYScene(baseSurfaceView);
            } else if (TextUtils.equals(planet.alias, "cxtx")) {
                baseScene = new CXTXScene(baseSurfaceView);
            } else if (TextUtils.equals(planet.alias, "pkjy")) {
                baseScene = new PKJYScene(baseSurfaceView);
            } else if (TextUtils.equals(planet.alias, "cxcy")) {
                baseScene = new CXCYScene(baseSurfaceView);
            }
        }


        activity.moveToNewScene(baseScene);
    }

    public void setTrainingData(Level level) {
        if (level != null) {
            if (!TextUtils.equals(planet.parent_planet.alias, "dzxl")) {
                PreferencesUtils.putInt(activity, planet.alias + ":best", level.level);
            }
        }

        startTraining();
    }
}
